import dayjs from 'dayjs';

enum Dictionaries {
  expire = '__expire__',
  permanent = 'permanent'
}

type Key = string; // key类型
interface Data<T> {
  // 格式化data类型
  value: T;
  [Dictionaries.expire]: Dictionaries.expire | number;
}

export class Storage {
  //TODO: recover
  prefix = '';
  private getKey = (key: Key) => {
    return key + this.prefix;
  };
  // 存储接受 key value 和过期时间 默认永久
  public set<T = any>(key: Key, value: T, expireTime?: { time: number; unit: 'day' | 'hour' | 'minute' | 'second' }) {
    // 格式化数据
    const data = {
      value,
      [Dictionaries.expire]: expireTime?.time ? dayjs().add(expireTime.time, expireTime.unit).valueOf() : ''
    };
    localStorage.setItem(this.getKey(key), JSON.stringify(data));
  }

  public get<T = any>(key: Key) {
    const value = localStorage.getItem(this.getKey(key));
    // 读出来的数据是否有效
    if (value) {
      const obj: Data<T> = JSON.parse(value);
      // 有效并且是数字类型 并且过期了 进行删除和提示
      if (typeof obj[Dictionaries.expire] === 'number' && dayjs(new Date()).isAfter(obj[Dictionaries.expire])) {
        this.remove(this.getKey(key));
        return null;
      } else {
        // 否则成功返回
        return obj.value;
      }
    } else {
      return null;
    }
  }

  public remove(key: Key) {
    localStorage.removeItem(this.getKey(key));
  }
}

export default new Storage();
